import apiClient from './index';

// 查询留言参数类型
export interface GetMessageListParams {
  offset: number;
  limit: number;
  sender_name?: string;
  receiver_name?: string;
  start_time?: string;
  end_time?: string;
  only_unread?: boolean;
}

// 单条留言信息类型
export interface MessageItem {
  id: number;
  message_direction: 'send' | 'receive';
  sender_id: number;
  sender_name: string;
  sender_role: string;
  receiver_id: number;
  receiver_name: string;
  receiver_role: string;
  content_preview: string;
  send_time: string;
  is_read: boolean;
  all_replies_read?: boolean;
}

// 留言列表返回结果类型
export interface GetMessageListResponse {
  code: number;
  content: {
    messages: MessageItem[];
    total: number;
  };
  msg: string;
}

/**
 * 获取留言列表
 */
export const getMessageList = async (
  params: GetMessageListParams
): Promise<GetMessageListResponse> => {
  const response = await apiClient.post<GetMessageListResponse>('/message/list', params);
  return response.data;
};

// 留言详情参数
export interface GetMessageDetailParams {
  message_id: number;
}

// 回复留言参数
export interface ReplyMessageParams {
  message_id: number;
  content: string;
}

// 主留言信息
export interface MainMessage {
  id: number;
  content: string;
  sender_name: string;
  receiver_name: string;
  send_time: string;
  is_read: boolean;
  message_direction: 'send' | 'receive';
}

// 回复信息
export interface ReplyItem {
  id: number;
  content: string;
  sender_name: string;
  receiver_name: string;
  send_time: string;
  is_read: boolean;
  message_direction: 'send' | 'receive';
}

// 留言详情返回结果
export interface GetMessageDetailResponse {
  code: number;
  content: {
    main_message: MainMessage;
    replies: ReplyItem[];
  };
  msg: string;
}

// 回复留言返回结果
export interface ReplyMessageResponse {
  code: number;
  content: {
    message: string;
    reply_id: number;
  };
  msg: string;
}

/**
 * 获取留言详情
 */
export const getMessageDetail = async (
  params: GetMessageDetailParams
): Promise<GetMessageDetailResponse> => {
  const response = await apiClient.post<GetMessageDetailResponse>('/message/detail', params);
  return response.data;
};

/**
 * 回复留言
 */
export const replyMessage = async (
  params: ReplyMessageParams
): Promise<ReplyMessageResponse> => {
  const response = await apiClient.post<ReplyMessageResponse>('/message/reply', params);
  return response.data;
};

// 发送留言参数
export interface SendMessageParams {
  receiver_ids: number[];
  content: string;
}

// 发送留言返回结果
export interface SendMessageResponse {
  code: number;
  content: {
    message_id: number;
    message: string;
  };
  msg: string;
}

/**
 * 发送新留言
 */
export const sendMessage = async (
  params: SendMessageParams
): Promise<SendMessageResponse> => {
  const response = await apiClient.post<SendMessageResponse>('/message/send', params);
  return response.data;
};